<template>
  <view class="scroll-item" @click="changeBtn(drawData)">
    <view class="scroll-item-img">
      <img
        style="width: 168rpx; height: 224rpx"
        :src="itemObj.frontUrl"
        alt=""
      />
    </view>
    <view class="scroll-item-details">
      <view class="item-day">
        <view class="time-style">
          {{ setDateTime(drawData.activitySelectionStartTime) }}
        </view>
        <view
          class="item-status"
          style="font-family: NotoSansSC-Medium"
          :style="{ color: drawData.titleColor }"
        >
          {{ drawData.title }}
        </view>
      </view>
      <view
        style="
          display: flex;
          justify-content: space-between;
          flex-direction: column;
          flex: 1;
        "
      >
        <text class="name-style" style="">{{
          drawData.subtitle || drawData.itemName
        }}</text>
        <view class="">
          <text
            @click="changeBtn(drawData)"
            class="text-details"
            :style="{ color: drawData.btnTextColor }"
            >{{
              drawData.btnText == "待支付"
                ? drawData.btnText + showDate
                : drawData.btnText
            }}</text
          >
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import api from "@/api/api";
import {
  SYSTEM_INFO,
  MERCHANT_INFO,
  CUSTOMER_INFO,
  USER_INFO,
  CART_KEY,
  USER_SPECICAL_INFO,
} from "@/utils/constant";
export default {
  props: {
    itemObj: {
      type: Object,
      default: () => {},
    },
    userOrderLists: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      DrawData: [],
      showDate: "",
      timer: null,
      drawData: {},
      _order: null,
    };
  },
  async mounted() {
    this.drawData = this.itemObj;
    // 活动信息
    this.infoData = await this.getDrawInfo(
      this.drawData.itemId,
      this.drawData.valueId
    );
    const orderLists = this.userOrderLists;
    this._order = null;
    for (let i = 0; i < orderLists.length; i++) {
      const _els = orderLists[i];
      if (
        _els &&
        _els.createTime &&
        this.infoData &&
        this.infoData.createTime
      ) {
        const otTime = _els.createTime.replace(/-/g, "/");
        const infoCreateTime = this.infoData.createTime.replace(/-/g, "/");
        // 活动时间内订单筛选
        if (
          _els.items[0].itemId == this.drawData.itemId &&
          this.infoData.createTime &&
          new Date(otTime).getTime() >
            new Date(infoCreateTime).getTime()
        ) {
          this._order = _els;
        }
      }
    }
    this.init();
  },
  methods: {
    async changeBtn(drawData) {
      const { itemId, valueId, activityStopTime } = drawData;
      const goodsOverTime = new Date(activityStopTime).getTime();
      const nowTime = await this.$commonFunction.getServerTime();
      // 活动未结束 可跳详情
      if (itemId && valueId && goodsOverTime > nowTime) {
        uni.navigateTo({
          url: "/pages/item/item?id=" + itemId + "&valueId=" + valueId,
        });
      }
    },
    async init() {
      try {
        if (this.drawData.status == "待支付") {
          // 加倒计时
          if (this._order) {
            let nowTime = new Date().getTime();
            let endTime = new Date(this._order.planEndTime).getTime();
            this.start(endTime - nowTime);
          } else {
            this.drawData.title = "活动结束";
            this.drawData.btnText = "查看详情";
            this.drawData.titleColor = "rgba(0, 0, 0, 0.54)";
            this.drawData.btnTextColor = "#000000";
          }
        }
      } catch (error) {
        console.log("historyInit", error);
      }
    },
    // 倒计时
    start(timestamp) {
      console.log(timestamp, "timestamp");
      // 避免可能出现的倒计时重叠情况
      this.clearTimer();
      if (timestamp <= 0) return;
      let seconds = timestamp / 1000;
      console.log(seconds, "seconds");
      this.timer = setInterval(() => {
        seconds--;
        // 发出change事件
        if (seconds < 0) {
          return this.end();
        }
        this.formatTime(seconds);
      }, 1000);
    },
    clearTimer() {
      if (this.timer) {
        // 清除定时器
        clearInterval(this.timer);
        this.$emit("onGetBalloutHistory");
        this.timer = null;
      }
    },
    // 停止倒计时
    end() {
      this.clearTimer();
      setTimeout(() => {
        this.showDate = "";
      }, 1000);
    },
    // 格式化时间
    formatTime(seconds) {
      // 小于等于0的话，结束倒计时
      seconds <= 0 && this.end();
      let [day, hour, minute, second] = [0, 0, 0, 0];
      // 判断是否显示“天”参数，如果不显示，将天部分的值，加入到小时中
      // hour为给后面计算秒和分等用的(基于显示天的前提下计算)
      hour = Math.floor(seconds / (60 * 60));
      minute = Math.floor(seconds / 60) - hour * 60 - day * 24 * 60;
      second =
        Math.floor(seconds) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
      // 如果小于10，在前面补上一个"0"
      hour = hour < 10 ? "0" + hour : hour;
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;

      this.showDate = ` ${hour}:${minute}:${second}`;
      console.log(this.showDate, "this.showDate");
    },
    async getDrawInfo(goodsId, valueId) {
      let customerInfo =
        uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo;
      let merchantInfo =
        uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
      let json = await api.getDrawInfo({
        method: "GET",
        query: {
          store_id: merchantInfo.cloudMerchantStoreId,
          merchant_id: merchantInfo.cloudMerchantId,
          customer_id: customerInfo ? customerInfo.customerId : "",
          item_id: goodsId,
          value_id: valueId,
        },
      });
      if (json.code === 1000) {
        return json.data;
      } else {
        return null;
      }
    },
    setDateTime(dateString = "") {
      // 将 "yyyy-MM-dd HH:mm:ss" 转换为 "yyyy/MM/dd HH:mm:ss"
      const formattedDateString = dateString.replace(/-/g, "/");
      const date = new Date(formattedDateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以加1，并且格式化为两位数
      const day = String(date.getDate()).padStart(2, "0"); // 格式化为两位数

      return `${year}年${month}月${day}日`;
    },
  },
};
</script>

<style lang="scss" scoped>
.scroll-item {
  display: flex;
  padding: 16rpx 0;
  background-color: #fafafa;

  .scroll-item-img {
    width: 168rpx;
    height: 224rpx;
  }
}

.scroll-item-details {
  // margin: 32rpx 32rpx 32rpx 0;
  margin: 16rpx 32rpx 16rpx 4rpx;
  flex-direction: column;
  display: flex;
  width: 360rpx;
  // margin-left: 14rpx;

  .item-day {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 9rpx;
  }

  .text-details {
    font-size: 24rpx;
    font-weight: 400;
    color: #000000;
    line-height: 20px;
    height: 42rpx;
    display: inline-block;
    text-decoration: underline;
    text-underline-offset: 4px;
    line-height: 1;
    font-family: "FrankNew-Regular", "NotoSansSC-Regular";
  }

  .name-style {
    margin-bottom: 60rpx;
    font-family: "FrankNew-Regular", "NotoSansSC-Regular";
    white-space: nowrap;
    /* 不换行 */
    overflow: hidden;
    /* 隐藏超出的内容 */
    text-overflow: ellipsis;
    /* 用省略号表示被截断的文字 */
    max-width: 100%;
  }

  .time-style {
    font-family: FrankNew-Regular, NotoSansSC-Regular;
    color: #757575;
    font-weight: 400;
    font-size: 24rpx;
    line-height: 40rpx;
  }
}
</style>
